package com.xuan.chatroom.controller;


import com.xuan.chatroom.constants.Constant;
import com.xuan.chatroom.model.MessageSession;
import com.xuan.chatroom.model.Result;
import com.xuan.chatroom.model.User;
import com.xuan.chatroom.service.MessageSessionService;
import com.xuan.chatroom.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/session")
public class MessageSessionController {
    @Autowired
    private MessageSessionService sessionService;

    @RequestMapping("/getSessionList")
    public List<MessageSession> getMessageSessionList(@RequestHeader(Constant.USER_TOKEN_HEADER) String token) {
        // 1. 从 header的 token中获取 userId
        int userId = JwtUtil.getIdFromToken(token);

        // 2. 根据 userId 获取所有存在关联的会话
        List<MessageSession> messageSessionList = sessionService.getMessageSessionList(userId);
        return messageSessionList;
    }


    @RequestMapping("/addSession")
    public Result addSession(Integer toUserId, @RequestHeader(Constant.USER_TOKEN_HEADER) String token) {
        log.info("[toUserId]: " + toUserId);
        // 1. 从 token 中获取 userId
        int userId = JwtUtil.getIdFromToken(token);

        // 2. 往会话表 及 会话-用户关系表 新增记录
        // 返回的data数据为 sessionId
        return sessionService.addSession(toUserId, userId);
    }
}
